#!/bin/bash

# ========================================
# 腾讯云 COS 挂载脚本（交互式安全增强版）
# 特性：
#   - 运行时输入密钥，避免明文泄露
#   - 手动输入下载链接（支持镜像代理）
#   - 支持 install / uninstall
#   - systemd 开机自启
# ========================================

set -e

# ============ 全局变量 =============
MOUNT_POINT="/sync"
PASSWD_FILE="/etc/passwd-cosfs"
SERVICE_NAME="cos-mount"
SYSTEMD_SERVICE="/etc/systemd/system/${SERVICE_NAME}.service"

# 用户输入
BUCKET_NAME=""
REGION=""
SECRET_ID=""
SECRET_KEY=""
DEB_URL=""
DEB_PACKAGE=""

# cosfs 实际路径（动态检测）
COSFS_BIN=""
# ====================================

# 获取输入（带默认值）
read_input() {
    local prompt="$1"
    local default="$2"
    local var_name="$3"
    local value
    if [ -z "$default" ]; then
        read -p "$prompt: " value
    else
        read -p "$prompt [$default]: " value
        value="${value:-$default}"
    fi
    eval "$var_name='$value'"
}

# 交互式获取配置
get_config() {
    echo "🔐 请输入腾讯云 COS 配置信息："
    read_input "存储桶名称" "" BUCKET_NAME
    read_input "地域（如 ap-beijing, ap-shanghai）" "ap-beijing" REGION
    read_input "SecretId" "" SECRET_ID
    read_input "SecretKey" "" SECRET_KEY

    if [ -z "$BUCKET_NAME" ] || [ -z "$SECRET_ID" ] || [ -z "$SECRET_KEY" ]; then
        echo "❌ 错误：Bucket Name、SecretId 和 SecretKey 不能为空！"
        exit 1
    fi

    echo
    echo "🌐 请输入 cosfs .deb 安装包下载链接"
    echo "💡 示例（Ubuntu 24.04）："
    echo "   官方: https://github.com/tencentyun/cosfs/releases/download/v1.0.24/cosfs_1.0.24-ubuntu24.04_amd64.deb"
    echo "   镜像: https://mirror.ghproxy.com/https://github.com/tencentyun/cosfs/releases/download/v1.0.24/cosfs_1.0.24-ubuntu24.04_amd64.deb"
    read_input "下载链接" "" DEB_URL

    if [ -z "$DEB_URL" ]; then
        echo "❌ 下载链接不能为空！"
        exit 1
    fi

    # 自动从 URL 提取文件名
    DEB_PACKAGE=$(basename "$DEB_URL")
    echo "✅ 将使用安装包: $DEB_PACKAGE"
}

# 自动检测 Ubuntu 版本（仅作提示）
detect_ubuntu_version() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        echo "🔍 检测到系统: $NAME $VERSION_ID ($ID)"
        echo "💡 推荐使用对应版本的 cosfs 包："
        case $VERSION_ID in
            "24.04")
                echo "   https://mirror.ghproxy.com/https://github.com/tencentyun/cosfs/releases/download/v1.0.24/cosfs_1.0.24-ubuntu24.04_amd64.deb"
                ;;
            "22.04")
                echo "   https://mirror.ghproxy.com/https://github.com/tencentyun/cosfs/releases/download/v1.0.24/cosfs_1.0.24-ubuntu22.04_amd64.deb"
                ;;
            "20.04")
                echo "   https://mirror.ghproxy.com/https://github.com/tencentyun/cosfs/releases/download/v1.0.24/cosfs_1.0.24-ubuntu20.04_amd64.deb"
                ;;
            *)
                echo "   请确认是否有适配版本"
                ;;
        esac
    else
        echo "⚠️ 无法检测系统版本"
    fi
    echo
}

# 安装 cosfs
install_cosfs() {
    echo "🔄 开始安装 cosfs..."

    sudo apt-get update
    sudo apt-get install -y gdebi-core wget lsb-release fuse

    if [ ! -f "$DEB_PACKAGE" ]; then
        echo "📥 正在下载: $DEB_URL"
        wget -O "$DEB_PACKAGE" "$DEB_URL" || {
            echo "❌ 下载失败，请检查链接或网络"
            exit 1
        }
        echo "✅ 下载成功: $DEB_PACKAGE"
    else
        echo "✅ 已存在 $DEB_PACKAGE，跳过下载"
    fi

    echo "📦 安装 deb 包..."
    sudo gdebi --non-interactive "$DEB_PACKAGE" > /dev/null 2>&1 || {
        sudo dpkg -i "$DEB_PACKAGE"
        sudo apt-get install -f -y
    }

    # 检测实际安装路径
    if command -v cosfs &> /dev/null; then
        COSFS_BIN=$(which cosfs)
        echo "✅ cosfs 已安装: $COSFS_BIN"
    else
        echo "❌ cosfs 安装失败！未找到可执行文件"
        echo "💡 请尝试手动运行: dpkg -L cosfs | grep bin/cosfs"
        exit 1
    fi

    # 确保 /usr/bin/cosfs 存在（systemd 默认路径）
    if [ "$COSFS_BIN" != "/usr/bin/cosfs" ]; then
        echo "🔧 创建软链接: /usr/bin/cosfs -> $COSFS_BIN"
        sudo ln -sf "$COSFS_BIN" /usr/bin/cosfs
    fi

    # 验证
    if [ ! -x /usr/bin/cosfs ]; then
        echo "❌ /usr/bin/cosfs 不存在或不可执行"
        exit 1
    fi

    echo "✅ cosfs 可执行路径已准备: /usr/bin/cosfs"
    /usr/bin/cosfs --version
}

# 配置凭证
configure_credentials() {
    echo "🔐 配置 COS 凭证..."
    echo "${BUCKET_NAME}:${SECRET_ID}:${SECRET_KEY}" | sudo tee "$PASSWD_FILE" > /dev/null
    sudo chmod 600 "$PASSWD_FILE"
    echo "✅ 凭证已保存至 $PASSWD_FILE"
}

# 创建挂载点
create_mount_point() {
    echo "📁 创建挂载目录 $MOUNT_POINT"
    sudo mkdir -p "$MOUNT_POINT"
    echo "✅ 目录准备就绪"
}

# 配置 systemd 服务
setup_systemd_service() {
    COSFS_URL="https://cos.${REGION}.myqcloud.com"

    echo "⚙️ 配置 systemd 服务: $SERVICE_NAME.service"

    cat <<EOF | sudo tee "$SYSTEMD_SERVICE" > /dev/null
[Unit]
Description=COSFS Mount Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/bin/cosfs ${BUCKET_NAME} ${MOUNT_POINT} -ourl=${COSFS_URL} -oallow_other -ouse_cache=/tmp -omax_stat_cache_size=100000 -f
ExecStop=/bin/fusermount -u ${MOUNT_POINT}
Restart=always
User=root
Group=root
Environment="HTTP_PROXY="
Environment="HTTPS_PROXY="
Environment="NO_PROXY=localhost,127.0.0.1"

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    sudo systemctl enable "$SERVICE_NAME" > /dev/null 2>&1 || true
    echo "✅ systemd 服务已创建并启用开机自启"
}

# 启动服务
start_service() {
    echo "🚀 启动 COS 挂载服务..."
    sudo systemctl start "$SERVICE_NAME"
    sleep 3

    if sudo systemctl is-active --quiet "$SERVICE_NAME"; then
        echo "✅ 服务已启动"
        if mount | grep -q "$MOUNT_POINT"; then
            echo "📁 成功挂载到 $MOUNT_POINT"
        else
            echo "⚠️  挂载点未显示，可查看日志: journalctl -u $SERVICE_NAME.service -b"
        fi
    else
        echo "❌ 服务启动失败，请查看日志:"
        echo "   journalctl -u $SERVICE_NAME.service -b"
        exit 1
    fi
}

# 安装主函数
install() {
    detect_ubuntu_version
    get_config

    echo
    echo "🔍 即将安装，确认信息："
    echo "   存储桶: $BUCKET_NAME"
    echo "   地域: $REGION"
    echo "   下载链接: $DEB_URL"
    echo "   挂载点: $MOUNT_POINT"
    echo
    read -p "是否继续？(y/N): " confirm
    if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
        echo "🛑 已取消"
        exit 0
    fi

    install_cosfs
    configure_credentials
    create_mount_point
    setup_systemd_service
    start_service

    echo
    echo "🎉 安装完成！"
    echo "📁 本地路径: $MOUNT_POINT"
    echo "📌 管理命令:"
    echo "   systemctl status cos-mount.service"
    echo "   journalctl -u cos-mount.service -b"
}

# 卸载函数
uninstall() {
    echo "⚠️  此操作将停止并卸载 COS 挂载服务"
    read -p "确定要卸载吗？(y/N): " confirm
    if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
        echo "🛑 已取消"
        exit 0
    fi

    if systemctl is-active --quiet "$SERVICE_NAME"; then
        sudo systemctl stop "$SERVICE_NAME"
        echo "✅ 服务已停止"
    fi

    if systemctl is-enabled "$SERVICE_NAME" > /dev/null 2>&1; then
        sudo systemctl disable "$SERVICE_NAME"
        echo "✅ 已禁用开机自启"
    fi

    if mount | grep -q "$MOUNT_POINT"; then
        sudo fusermount -u "$MOUNT_POINT" 2>/dev/null || echo "⚠️ 卸载挂载点失败"
        echo "📁 挂载点已卸载"
    fi

    sudo rm -f "$SYSTEMD_SERVICE"
    sudo systemctl daemon-reload
    echo "🗑️ systemd 服务文件已删除"

    if [ -f "$PASSWD_FILE" ]; then
        sudo rm -f "$PASSWD_FILE"
        echo "🔐 凭证文件已清除"
    fi

    # 删除软链接（不影响原文件）
    if [ -L "/usr/bin/cosfs" ]; then
        sudo rm -f /usr/bin/cosfs
        echo "🔗 软链接 /usr/bin/cosfs 已删除"
    fi

    echo "💡 提示：本地目录 $MOUNT_POINT 已保留，如需删除请手动执行"
    echo "✅ 卸载完成！"
}

# 帮助
show_help() {
    echo "Usage: $0 {install|uninstall|help}"
    echo ""
    echo "命令说明:"
    echo "  install     交互式安装 COS 挂载服务"
    echo "  uninstall   卸载服务（需确认）"
    echo "  help        显示此帮助"
}

# ========== 主入口 ==========
case "$1" in
    install)
        install
        ;;
    uninstall)
        uninstall
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        echo "❌ 未知命令: $1"
        show_help
        exit 1
        ;;
esac